package com.drama.outtake.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.drama.outtake.MyException;
import com.drama.outtake.common.Result;
import com.drama.outtake.domain.LoginFormDTO;
import com.drama.outtake.dto.LoginDto;
import com.drama.outtake.service.ILoginService;
import com.drama.outtake.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author : 李先均
 * @Date 2023/3/2 13:47
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class LoginController {
    private final ILoginService loginService;
    @Resource
    private IUserService userService;

    @PostMapping("/login/wxLogin")
    public Result<LoginDto> wxLogin(@RequestBody Map<String, String> map) {
        log.info("(post):/login/wxLogin, parameters are = {}", map);
        String phoneCode = map.getOrDefault("phoneCode", null);
        String loginCode = map.getOrDefault("loginCode", null);
        if (loginCode == null) {
            throw new MyException("登录所需的code失效");
        }
        String sessionKey = JSON.parseObject(loginService.getOpenIdAndSessionKey(loginCode)).getString("session_key");
        LoginDto loginDto = new LoginDto(loginService.wxLogin(phoneCode), sessionKey);
        String tokenValue = StpUtil.getTokenValue();
        loginDto.setSessionKey(tokenValue);
        return Result.ok(loginDto);
    }

    /**
     * 发送手机验证码
     */
    @PostMapping("/login/code")
    public Result sendCode(@RequestParam("phoneCode") String phone, HttpSession session) {
        // 发送短信验证码并保存验证码
        return userService.sendCode(phone, session);
    }

    /**
     * 手机号登录功能
     */
    @PostMapping("/login/phoneLogin")
    public Result login(@RequestParam("phoneCode") String phone, @RequestParam("loginCode") String code) {
        // 实现登录功能
        LoginFormDTO loginForm = new LoginFormDTO();
        loginForm.setPhone(phone);
        loginForm.setCode(code);
        return userService.login(loginForm);
    }

    @GetMapping("/logout")
    public Result<Object> logout() {
        StpUtil.logout();
        return Result.ok();
    }
}
